package qqserver.service;

import qqcommon.Message;
import qqcommon.MessageType;
import utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Iterator;

public class SendServerMessageThread extends Thread {

    @Override
    public void run() {
        while (true) {
            System.out.println("是否推送消息(Y/N),输入exit退出消息推送服务：");
            String isSendMes = Utility.readString(10);
            if ("Y".equals(isSendMes) || "y".equals(isSendMes)) {
                System.out.print("请输入服务端要推送的消息内容：");
                String content = Utility.readString(100);
                Message message1 = new Message();//服务端要发送回客户端的message1
                message1.setMesType(MessageType.MESSAGE_SEVER_MES);//设置推送消息的类型
                message1.setContent(content);//设置推送消息的内容

                ObjectOutputStream oos;
                Collection<ServerConnectThread> threads = ManageServerConnectThread.getHsm().values();//获取在线用户的所有线程
                Iterator<ServerConnectThread> it = threads.iterator();//在线用户线程集合
                while (it.hasNext()) {//遍历线程集合
                    try {
                        oos = new ObjectOutputStream(it.next().getSocket().getOutputStream());
                        oos.writeObject(message1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("向" + threads.size() + "个在线用户推送了消息");
            } else if ("exit".equals(isSendMes)) {
                System.out.println("消息推送服务关闭");
                break;//服务推送线程
            }
        }
    }
}
